<template>
  <match-parent class="message-private-chat-list">
    <scroll-up :has-more="hasMore" :loading="loading" @load="loadMore">
      <mu-list textline="two-line">
        <mu-list-item v-for="item in chatList" :key="item.right_id" avatar button :ripple="true" @click="handleClick(item)">
          <mu-list-item-action>
            <mu-badge v-if="item.received_count - item.read_count > 0" :content="`${item.received_count - item.read_count}`" circle color="secondary">
              <mu-avatar>
                <img :src="item.user.avatar_url">
              </mu-avatar>
            </mu-badge>
            <mu-avatar v-else>
              <img :src="item.user.avatar_url">
            </mu-avatar>
          </mu-list-item-action>
          <mu-list-item-content>
            <mu-list-item-title>{{ item.user.realname }}</mu-list-item-title>
            <mu-list-item-sub-title>{{ item.last_message.content }}</mu-list-item-sub-title>
          </mu-list-item-content>
        </mu-list-item>
      </mu-list>
    </scroll-up>
  </match-parent>
</template>

<script>
import api from '@/api'
import MatchParent from '@/components/MatchParent'
import ScrollUp from '@/components/ScrollUp'
import { chatListAppendUser } from './util'

export default {
  name: 'MessagePrivateChatList',
  components: {
    MatchParent,
    ScrollUp
  },
  data() {
    return {
      current_page: 0,
      total: 0,
      list: [],
      loading: false
    }
  },
  computed: {
    chatList() {
      return this.list.map(chatListAppendUser)
    },
    hasMore() {
      return this.list.length < this.total
    }
  },
  created() {
    this.loadMore()
  },
  methods: {
    // 刷新
    async refresh() {
      this.loading = true
      try {
        const page = 1
        const data = await api.fetchChatList(page)
        this.list = data.data
        this.total = parseInt(data.total)
        this.current_page = parseInt(data.current_page)
      } catch (err) {
        this.$apiCatch(err)
      }
      this.loading = false
    },
    // 消息列表加载更多
    async loadMore() {
      this.loading = true
      try {
        const page = parseInt(this.current_page) + 1
        const data = await api.fetchChatList(page)
        this.list = this.list.concat(data.data)
        this.total = parseInt(data.total)
        this.current_page = parseInt(data.current_page)
      } catch (err) {
        this.$apiCatch(err)
      }
      this.loading = false
    },
    // 点击某个消息行
    handleClick({ right_id }) {
      this.$emit('chat', right_id)
    }
  }
}
</script>
